<?php
namespace App\Services;

use App\Models\SysConfig;
use Illuminate\Support\Facades\Cache;

/**
 * 系统配置服务类
 * @package App\Services
 */
class SysConfigService
{
    //微信行业配置
    const TYPE_WX_TEMPLATE_INDUSTRY = 'wx_templatemsg_industrys_set';
    const TYPE_WX_AUTO_REPLY = 'wx_auto_reply';

    /**
     * 获取缓存列表
     * @param bool $isRefresh
     * @return mixed
     */
    public function getCacheList($isRefresh = false)
    {
        $cacheKey = 'sysconfig';
        $cacheData = Cache::get($cacheKey);
        if (!$cacheData || $isRefresh){
            $list = SysConfig::all()->toArray();
            $cacheData = [];
            if ($list){
                foreach ($list as $v){
                    $cacheData[$v['key']] = $v['val'];
                }
            }
            Cache::put($cacheKey, $cacheData, 60);
        }
        return $cacheData;
    }

    /**
     * 设置配置值
     * @param $key
     * @param $val
     * @return mixed
     */
    public function set($key, $val)
    {
        $rs = SysConfig::updateOrCreate(['key'=>$key], ['val'=>$val]);
        //更新缓存
        $this->getCacheList(true);
        return $rs;
    }

    /**
     * 获取配置值
     * @param $key
     * @return array
     */
    public function get($key)
    {
        $configList = $this->getCacheList();
        return isset($configList[$key]) ? $configList[$key] : [];
    }
}